<template>
  <div class="home">
    <!-- 头部导航 -->
    <header class="header">
      <div class="header-content">
        <h1>🎓 少儿英语辅助学习平台</h1>
        <div class="user-section">
          <div v-if="user" class="user-info">
            <span class="welcome">欢迎，{{ user.nickname || user.username }} ({{ getRoleName(user.role) }})</span>
            <!-- 添加组件测试按钮 -->
            <button @click="showComponentTest = true" class="test-btn">
              🔧 组件测试
            </button>
            <button @click="logout" class="logout-btn">退出</button>
          </div>
          <div v-else class="auth-buttons">
            <button @click="showLogin = true" class="login-btn">登录</button>
            <button @click="showRegister = true" class="register-btn">注册</button>
          </div>
        </div>
      </div>
    </header>

    <!-- 主要内容 -->
    <main class="main-content">
      <div class="hero-section">
        <h1>让英语学习变得有趣而高效</h1>
        <p class="subtitle">智能语音识别 · 语言学协助工具 · 过关式游戏体验</p>
      </div>

      <!-- 根据用户角色显示不同内容 -->
      <div class="role-content">
        <!-- 未登录状态 -->
        <div v-if="!user" class="guest-content">
          <div class="welcome-message">
            <h2>欢迎使用少儿英语辅助学习平台</h2>
            <p>请登录或注册后使用相应功能</p>
          </div>
          <div class="features-grid">
            <div class="feature-card" @click="showLogin = true">
              <div class="feature-icon">👂</div>
              <h3>磨耳朵听力</h3>
              <p>通过听力训练提升英语语感，适合3-8岁孩子</p>
            </div>

            <div class="feature-card" @click="showLogin = true">
              <div class="feature-icon">🎮</div>
              <h3>游戏关卡</h3>
              <p>在游戏中学习英语单词和语法，寓教于乐</p>
            </div>

            <div class="feature-card" @click="showLogin = true">
              <div class="feature-icon">👨‍👩‍👧‍👦</div>
              <h3>家长监控</h3>
              <p>实时查看孩子学习进度，零压力陪伴</p>
            </div>
          </div>
        </div>

        <!-- 管理员界面 -->
        <div v-else-if="user.role === 'admin'" class="admin-content">
          <AdminManagement />
        </div>

        <!-- 家长界面 -->
        <div v-else-if="user.role === 'parent'" class="parent-content">
          <h2>👨‍👩‍👧‍👦 家长监控中心</h2>
          <p class="role-description">实时了解孩子学习情况，陪伴孩子快乐成长</p>
          <div class="parent-features">
            <div v-if="hasPermission('parent:child:view')" class="feature-card" @click="viewChildProgress">
              <div class="feature-icon">📈</div>
              <h3>学习进度</h3>
              <p>查看孩子的学习情况和进步</p>
              <div class="action-btn">查看详情</div>
            </div>

            <div v-if="hasPermission('parent:plan:edit')" class="feature-card" @click="setStudyPlan">
              <div class="feature-icon">📅</div>
              <h3>学习计划</h3>
              <p>为孩子制定个性化学习计划</p>
              <div class="action-btn">制定计划</div>
            </div>

            <div class="feature-card" @click="contactTeacher">
              <div class="feature-icon">💬</div>
              <h3>联系老师</h3>
              <p>与老师沟通孩子学习情况</p>
              <div class="action-btn">立即联系</div>
            </div>
          </div>
        </div>

        <!-- 幼儿界面 -->
        <div v-else-if="user.role === 'child'" class="child-content">
          <h2>🎒 幼儿学习中心</h2>
          <p class="role-description">快乐学习英语，在游戏中成长！</p>
          <div class="child-features">
            <div v-if="hasPermission('learning:listening:view')" class="feature-card" @click="startLearning('listening')">
              <div class="feature-icon">👂</div>
              <h3>磨耳朵听力</h3>
              <p>听儿歌、故事，提升英语语感</p>
              <div class="progress">今日进度: 60%</div>
            </div>

            <div v-if="hasPermission('learning:reading:view')" class="feature-card" @click="startLearning('reading')">
              <div class="feature-icon">📚</div>
              <h3>绘本阅读</h3>
              <p>阅读有趣的英文绘本故事</p>
              <div class="progress">已阅读: 5本</div>
            </div>

            <div v-if="hasPermission('learning:game:view')" class="feature-card" @click="startLearning('game')">
              <div class="feature-icon">🎮</div>
              <h3>单词游戏</h3>
              <p>玩游戏学单词，快乐记忆</p>
              <div class="progress">{{ gameProgressText }}</div>
            </div>

            <!-- 如果没有权限时显示提示 -->
            <div v-if="!hasAnyLearningPermission" class="no-permission-message">
              <div class="empty-state">
                <div class="empty-icon">🔒</div>
                <h3>暂无学习权限</h3>
                <p>请联系家长或老师为您开通学习功能</p>
              </div>
            </div>
          </div>
        </div>

        <!-- 教师界面 -->
        <div v-else-if="user.role === 'teacher'" class="teacher-content">
          <h2>👩‍🏫 教师管理中心</h2>
          <p class="role-description">管理班级教学，关注每个孩子的成长</p>
          <div class="teacher-features">
            <div v-if="hasPermission('teaching:class:view')" class="feature-card" @click="manageStudents">
              <div class="feature-icon">👨‍🎓</div>
              <h3>学生管理</h3>
              <p>管理班级学生信息和学习情况</p>
              <div class="action-btn">管理学生</div>
            </div>

            <div v-if="hasPermission('teaching:content:edit')" class="feature-card" @click="createContent">
              <div class="feature-icon">📝</div>
              <h3>教学内容</h3>
              <p>创建和编辑学习材料和课件</p>
              <div class="action-btn">创建内容</div>
            </div>

            <div v-if="hasPermission('teaching:report:view')" class="feature-card" @click="viewReports">
              <div class="feature-icon">📊</div>
              <h3>学习报告</h3>
              <p>查看班级学习情况统计分析</p>
              <div class="action-btn">查看报告</div>
            </div>
          </div>
        </div>

        <!-- 未知角色或角色为空 -->
        <div v-else class="unknown-role">
          <h2>欢迎使用少儿英语学习平台</h2>
          <div class="error-message">
            <p>⚠️ 用户角色配置异常</p>
            <p>当前角色: <strong>{{ user.role || '未分配' }}</strong></p>
            <p>请联系系统管理员配置正确的角色权限</p>
          </div>
          <div class="debug-info" v-if="user">
            <h4>调试信息：</h4>
            <p>用户名: {{ user.username }}</p>
            <p>昵称: {{ user.nickname }}</p>
            <p>角色: {{ user.role }}</p>
            <p>权限: {{ userPermissions.join(', ') }}</p>
          </div>
        </div>
      </div>

      <!-- 组件测试面板 -->
      <ComponentTest
        v-if="showComponentTest"
        @close="showComponentTest = false"
      />

      <!-- 系统信息 -->
      <div class="app-info">
        <h3>🏢 系统信息</h3>
        <div class="info-grid">
          <div class="info-item">
            <span class="label">版本:</span>
            <span class="value">{{ appInfo?.data?.version || '1.0.0' }}</span>
          </div>
          <div class="info-item">
            <span class="label">状态:</span>
            <span class="value status-active">{{ appInfo?.data?.status || '服务运行正常' }}</span>
          </div>
          <div class="info-item">
            <span class="label">时间:</span>
            <span class="value">{{ formatTime(appInfo?.data?.timestamp) }}</span>
          </div>
        </div>
      </div>
    </main>

    <!-- 登录弹窗 -->
    <LoginModal
      v-if="showLogin"
      @close="showLogin = false"
      @login-success="handleLoginSuccess"
    />

    <!-- 注册弹窗 -->
    <RegisterModal
      v-if="showRegister"
      @close="showRegister = false"
      @register-success="handleRegisterSuccess"
      @show-login="showLoginModal"
    />

    <!-- 成功提示消息 -->
    <div v-if="showSuccessMessage" class="success-message" :class="messageType">
      <div class="success-content">
        <span class="success-icon">{{ messageIcon }}</span>
        <span>{{ successMessage }}</span>
        <button class="close-success" @click="showSuccessMessage = false">×</button>
      </div>
    </div>
  </div>
</template>

<script>
import { childEnglishApi } from '@/api/childEnglishApi';
import { userService } from '@/services/userService';
import LoginModal from '@/components/LoginModal.vue';
import ComponentTest from '@/components/ComponentTest.vue';
import AdminManagement from '@/components/AdminManagement.vue';
import RegisterModal from '@/components/RegisterModal.vue';

export default {
  name: 'HomePage',
  components: {
    LoginModal,
    ComponentTest,
    AdminManagement,
    RegisterModal
  },
  data() {
    return {
      appInfo: null,
      user: null,
      showLogin: false,
      showRegister: false,
      showComponentTest: false,
      userPermissions: [], // 存储用户权限列表
      // 成功提示消息相关
      showSuccessMessage: false,
      successMessage: '',
      messageType: 'success',
      gameProgress: {
        completed: 0,
        total: 75,
        percentage: 0
      }
    };
  },
  computed: {
    // 检查是否有任何学习权限
    hasAnyLearningPermission() {
      const learningPermissions = [
        'learning:listening:view',
        'learning:reading:view',
        'learning:game:view'
      ];
      return learningPermissions.some(perm => this.userPermissions.includes(perm));
    },
    gameProgressText() {
      return `已通关: ${this.gameProgress.completed}/${this.gameProgress.total}关 (${this.gameProgress.percentage}%)`;
    }
  },
  async mounted() {
    this.loadAppInfo();
    this.checkLoginStatus();
    this.loadGameProgress();
    
    // 不再监听storage事件，因为现在使用sessionStorage，每个标签页独立会话
    // 移除storage事件监听器，确保标签页之间不会相互影响
    
    // 监听标签页关闭事件，清理在线用户记录
    window.addEventListener('beforeunload', this.handleBeforeUnload);
    // 监听页面隐藏事件（切换标签页、最小化窗口等）
    document.addEventListener('visibilitychange', this.handleVisibilityChange);
    
    // 监听localStorage变化，更新游戏进度
    window.addEventListener('storage', this.handleStorageChange);
    // 定期更新游戏进度（因为localStorage变化事件可能不会在同一标签页触发）
    this.gameProgressInterval = setInterval(() => {
      this.loadGameProgress();
    }, 2000);
    
    // 监听路由变化，从游戏页面返回时更新进度
    this.$watch('$route', () => {
      this.loadGameProgress();
    });
  },
  
  beforeUnmount() {
    // 不再需要移除storage事件监听器
    // 清理事件监听器
    window.removeEventListener('beforeunload', this.handleBeforeUnload);
    document.removeEventListener('visibilitychange', this.handleVisibilityChange);
    window.removeEventListener('storage', this.handleStorageChange);
    
    // 清理定时器
    if (this.gameProgressInterval) {
      clearInterval(this.gameProgressInterval);
    }
    
    // 组件卸载时也尝试清理在线用户记录
    this.cleanupOnlineUser();
  },
  methods: {
    async loadAppInfo() {
      try {
        const response = await childEnglishApi.getAppInfo();
        this.appInfo = response;
      } catch (error) {
        console.error('获取应用信息失败:', error);
        // 提供默认应用信息
        this.appInfo = {
          code: 200,
          data: {
            version: '1.0.0',
            status: '服务运行正常',
            timestamp: new Date()
          }
        };
      }
    },

    async checkLoginStatus() {
      const userData = userService.getCurrentUser();
      console.log('从sessionStorage获取的用户数据:', userData);

      if (userData) {
        // 检查当前页面期望的角色（如果有的话）
        const currentPath = this.$route.path;
        const expectedRole = this.getExpectedRoleForPath(currentPath);
        
        // 如果当前路径需要特定角色，但用户角色不匹配，提示用户
        if (expectedRole && userData.role !== expectedRole) {
          console.warn(`当前路径需要${expectedRole}角色，但用户是${userData.role}角色`);
          // 不清除用户信息，但提示用户可能需要切换账号
        }
        
        this.user = userData;
        console.log('当前用户角色:', userData.role);

        // 登录后获取用户权限
        await this.loadUserPermissions();
        // 加载游戏进度
        this.loadGameProgress();
      } else {
        this.user = null;
        this.userPermissions = [];
        this.gameProgress = { completed: 0, total: 75, percentage: 0 };
      }
    },
    
    loadGameProgress() {
      // 计算所有难度的总完成关卡数
      let totalCompleted = 0;
      const difficulties = ['easy', 'medium', 'hard'];
      
      difficulties.forEach(difficulty => {
        const key = `game_progress_${difficulty}`;
        const progress = JSON.parse(localStorage.getItem(key) || '{}');
        totalCompleted += progress.completedCount || 0;
      });
      
      const totalLevels = 75; // 所有模式关卡总和：20+25+30=75
      const percentage = totalLevels > 0 ? Math.round((totalCompleted / totalLevels) * 100) : 0;
      
      this.gameProgress = {
        completed: totalCompleted,
        total: totalLevels,
        percentage: percentage
      };
    },
    
    handleStorageChange(event) {
      // 如果localStorage中的游戏进度发生变化，更新显示
      if (event.key && event.key.startsWith('game_progress_')) {
        this.loadGameProgress();
      }
    },

    // 已移除handleStorageChange方法
    // 现在使用sessionStorage，每个标签页独立会话，不需要跨标签页同步用户数据

    // 根据路径获取期望的角色
    getExpectedRoleForPath(path) {
      if (path.includes('/admin') || path.includes('/management')) {
        return 'admin';
      } else if (path.includes('/teacher')) {
        return 'teacher';
      } else if (path.includes('/parent')) {
        return 'parent';
      } else if (path.includes('/child')) {
        return 'child';
      }
      return null;
    },

    async loadUserPermissions() {
      try {
        // 如果用户已登录，使用用户ID获取权限
        let response;
        if (this.user && this.user.id) {
          response = await childEnglishApi.getUserPermissions(this.user.id);
        } else {
          response = await childEnglishApi.getUserPermissions();
        }

        if (response.code === 200) {
          this.userPermissions = response.data.permissions || [];
          console.log('用户权限列表:', this.userPermissions);
        } else {
          console.error('获取用户权限失败:', response.message);
          // 使用默认权限作为后备
          this.setDefaultPermissions();
        }
      } catch (error) {
        console.error('获取用户权限异常:', error);
        // 使用默认权限作为后备
        this.setDefaultPermissions();
      }
    },

    setDefaultPermissions() {
      // 根据用户角色设置默认权限
      const defaultPermissions = {
        'admin': [
          'system:user:view', 'system:user:edit', 'system:user:delete',
          'system:role:view', 'system:role:edit', 'system:role:delete',
          'system:permission:view', 'system:permission:edit',
          'learning:listening:view', 'learning:reading:view', 'learning:game:view',
          'parent:child:view', 'parent:progress:view', 'parent:plan:edit',
          'teaching:class:view', 'teaching:content:edit', 'teaching:report:view'
        ],
        'parent': [
          'parent:child:view', 'parent:progress:view', 'parent:plan:edit'
        ],
        'child': [
          'learning:listening:view', 'learning:reading:view', 'learning:game:view'
        ],
        'teacher': [
          'teaching:class:view', 'teaching:content:edit', 'teaching:report:view'
        ]
      };

      this.userPermissions = defaultPermissions[this.user.role] || [];
      console.log('使用默认权限:', this.userPermissions);
    },

    // 检查用户是否有特定权限
    hasPermission(permissionCode) {
      return this.userPermissions.includes(permissionCode);
    },

    async handleLoginSuccess(user) {
      console.log('登录成功，用户信息:', user);
      this.user = user;
      this.showLogin = false;

      // 重新加载应用信息和用户权限
      await this.loadAppInfo();
      await this.loadUserPermissions();

      console.log('最终用户权限:', this.userPermissions);
      console.log('是否有游戏权限:', this.hasPermission('learning:game:view'));
      console.log('是否有听力权限:', this.hasPermission('learning:listening:view'));
      console.log('是否有阅读权限:', this.hasPermission('learning:reading:view'));
    },

    // 处理注册成功
    async handleRegisterSuccess(user) {
      console.log('注册成功，用户信息:', user);
      this.user = user;
      this.showRegister = false;

      // 重新加载应用信息和用户权限
      await this.loadAppInfo();
      await this.loadUserPermissions();

      console.log('最终用户权限:', this.userPermissions);
      this.showSuccess('注册成功！欢迎使用少儿英语学习平台', 'success');
    },

    // 显示登录模态框
    showLoginModal() {
      this.showRegister = false;
      this.showLogin = true;
    },

    async logout() {
      try {
        // 调用后端登出接口，清理在线用户记录和会话
        await childEnglishApi.logout();
        console.log("用户主动退出登录，已清理会话和在线状态");
      } catch (error) {
        console.error('登出请求失败:', error);
        // 即使失败也继续清理本地数据
      } finally {
        // 清理本地用户数据
        userService.clearUser();
        this.user = null;
        this.userPermissions = [];
        this.showComponentTest = false;
        this.showSuccess('已退出登录', 'success');
      }
    },

    // 处理标签页关闭事件
    handleBeforeUnload(event) {
      // 清理在线用户记录（使用同步方式确保请求能够发送）
      this.cleanupOnlineUser();
    },

    // 处理页面可见性变化
    handleVisibilityChange() {
      // 当页面变为隐藏时，不清理（因为可能只是切换标签页）
      // 只在页面卸载时清理
      if (document.visibilityState === 'hidden') {
        // 页面隐藏时，使用 sendBeacon 发送登出请求（作为备用方案）
        // 但主要清理还是在 beforeunload 中完成
      }
    },

    // 清理在线用户记录（页面关闭时调用）
    cleanupOnlineUser() {
      if (this.user) {
        // 使用 sendBeacon 或 fetch keepalive 确保请求能够发送
        const csrfToken = localStorage.getItem('csrfToken');
        const apiBaseUrl = window.location.origin.replace(':3000', ':8080');
        
        try {
          // 优先使用 fetch with keepalive（支持自定义请求头）
          if (fetch && typeof fetch === 'function') {
            fetch(`${apiBaseUrl}/logout`, {
              method: 'POST',
              credentials: 'include',
              keepalive: true, // 确保在页面卸载时也能完成请求
              headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': csrfToken || ''
              },
              body: JSON.stringify({})
            }).catch(() => {
              // 如果 fetch 失败，降级到 sendBeacon
              if (navigator.sendBeacon) {
                const formData = new FormData();
                if (csrfToken) {
                  formData.append('X-CSRF-TOKEN', csrfToken);
                }
                navigator.sendBeacon(`${apiBaseUrl}/logout`, formData);
              }
            });
          } else if (navigator.sendBeacon) {
            // 降级方案：使用 sendBeacon
            const formData = new FormData();
            if (csrfToken) {
              formData.append('X-CSRF-TOKEN', csrfToken);
            }
            navigator.sendBeacon(`${apiBaseUrl}/logout`, formData);
          }
        } catch (error) {
          console.error('清理在线用户记录失败:', error);
        }
      }
    },

    // 显示成功提示消息
    showSuccess(message, type = 'success') {
      this.successMessage = message;
      this.messageType = type;
      this.showSuccessMessage = true;

      setTimeout(() => {
        this.showSuccessMessage = false;
      }, 3000);
    },

    getRoleName(role) {
      const roleMap = {
        'admin': '管理员',
        'parent': '家长',
        'child': '幼儿',
        'teacher': '教师'
      };
      return roleMap[role] || (role ? role : '用户');
    },

    formatTime(timestamp) {
      if (!timestamp) return '--';
      if (typeof timestamp === 'string') {
        return timestamp;
      }
      return new Date(timestamp).toLocaleString('zh-CN');
    },

    // 幼儿功能
    startLearning(type) {
      const routeMap = {
        'listening': '/child/listening',
        'reading': '/child/reading',
        'game': '/child/game'
      };
      const route = routeMap[type];
      if (route) {
        this.$router.push(route);
      }
    },

    // 家长功能
    viewChildProgress() {
      this.$router.push('/parent/progress');
    },

    setStudyPlan() {
      this.$router.push('/parent/plan');
    },

    contactTeacher() {
      this.$router.push('/parent/contact');
    },

    // 老师功能
    manageStudents() {
      this.$router.push('/teacher/students');
    },

    createContent() {
      this.$router.push('/teacher/content');
    },

    viewReports() {
      this.$router.push('/teacher/reports');
    }
  }
};
</script>

<style scoped>
/* 头部样式 */
.header {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 15px 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.header h1 {
  color: #2c3e50;
  font-size: 1.8em;
  margin: 0;
}

.user-section {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.welcome {
  color: #2c3e50;
  font-weight: bold;
}

/* 认证按钮样式 */
.auth-buttons {
  display: flex;
  gap: 10px;
}

.login-btn, .logout-btn, .test-btn, .register-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.login-btn {
  background: #3498db;
  color: white;
}

.login-btn:hover {
  background: #2980b9;
  transform: translateY(-2px);
}

.register-btn {
  background: #27ae60;
  color: white;
}

.register-btn:hover {
  background: #219a52;
  transform: translateY(-2px);
}

.logout-btn {
  background: #e74c3c;
  color: white;
}

.logout-btn:hover {
  background: #c0392b;
  transform: translateY(-2px);
}

.test-btn {
  background: #9b59b6;
  color: white;
}

.test-btn:hover {
  background: #8e44ad;
  transform: translateY(-2px);
}

/* 主要内容 */
.main-content {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  min-height: calc(100vh - 80px);
}

.hero-section {
  text-align: center;
  margin-bottom: 50px;
  padding: 40px 0;
}

.hero-section h1 {
  color: white;
  font-size: 2.5em;
  margin-bottom: 10px;
  text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
}

.subtitle {
  color: #e0e0e0;
  font-size: 1.2em;
  font-style: italic;
}

/* 角色描述 */
.role-description {
  text-align: center;
  color: #7f8c8d;
  margin-bottom: 30px;
  font-size: 1.1em;
}

/* 功能网格 */
.features-grid, .parent-features, .child-features, .teacher-features {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 25px;
  margin-bottom: 40px;
}

.feature-card {
  background: white;
  border-radius: 15px;
  padding: 30px;
  text-align: center;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
  position: relative;
  overflow: hidden;
}

.feature-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.feature-card:hover {
  transform: translateY(-10px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
  border-color: #667eea;
}

.feature-icon {
  font-size: 3em;
  margin-bottom: 15px;
}

.feature-card h3 {
  color: #2c3e50;
  margin-bottom: 10px;
  font-size: 1.3em;
}

.feature-card p {
  color: #7f8c8d;
  line-height: 1.5;
  margin-bottom: 15px;
}

.progress {
  margin-top: 10px;
  padding: 8px;
  background: #ecf0f1;
  border-radius: 8px;
  font-size: 12px;
  color: #2c3e50;
  font-weight: bold;
}

.action-btn {
  margin-top: 10px;
  padding: 8px 16px;
  background: #3498db;
  color: white;
  border-radius: 6px;
  font-size: 12px;
  font-weight: bold;
  display: inline-block;
}

/* 无权限提示 */
.no-permission-message {
  grid-column: 1 / -1;
  text-align: center;
  padding: 40px;
}

.empty-state {
  background: white;
  padding: 40px;
  border-radius: 15px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.empty-icon {
  font-size: 4em;
  margin-bottom: 20px;
}

.empty-state h3 {
  color: #2c3e50;
  margin-bottom: 10px;
}

.empty-state p {
  color: #7f8c8d;
}

/* 角色特定内容 */
.role-content h2 {
  text-align: center;
  color: white;
  margin-bottom: 15px;
  font-size: 2em;
  text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
}

/* 欢迎消息 */
.welcome-message {
  text-align: center;
  margin-bottom: 40px;
  color: white;
}

.welcome-message h2 {
  font-size: 2.2em;
  margin-bottom: 10px;
}

.welcome-message p {
  font-size: 1.2em;
  opacity: 0.9;
}

/* 错误消息 */
.error-message {
  background: rgba(255, 255, 255, 0.9);
  padding: 20px;
  border-radius: 10px;
  text-align: center;
  margin-bottom: 20px;
}

.error-message p {
  margin: 5px 0;
  color: #e74c3c;
}

.debug-info {
  background: rgba(255, 255, 255, 0.8);
  padding: 15px;
  border-radius: 8px;
  margin-top: 20px;
}

.debug-info h4 {
  margin-bottom: 10px;
  color: #2c3e50;
}

.debug-info p {
  margin: 3px 0;
  color: #7f8c8d;
  font-size: 14px;
}

/* 系统信息 */
.app-info {
  background: rgba(255, 255, 255, 0.9);
  padding: 25px;
  border-radius: 12px;
  backdrop-filter: blur(10px);
  margin-top: 40px;
}

.app-info h3 {
  color: #2c3e50;
  margin-bottom: 15px;
  text-align: center;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 6px;
}

.label {
  font-weight: bold;
  color: #2c3e50;
}

.value {
  color: #5d6d7e;
}

.status-active {
  color: #27ae60;
  font-weight: bold;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 10px;
  }

  .header h1 {
    font-size: 1.5em;
  }

  .features-grid, .parent-features, .child-features, .teacher-features {
    grid-template-columns: 1fr;
  }

  .feature-card {
    padding: 20px;
  }

  .hero-section h1 {
    font-size: 2em;
  }

  .info-grid {
    grid-template-columns: 1fr;
  }

  .user-info {
    flex-direction: column;
    gap: 8px;
  }

  .auth-buttons {
    flex-direction: column;
    gap: 8px;
  }

  .test-btn, .logout-btn, .login-btn, .register-btn {
    width: 100%;
    margin: 2px 0;
  }
}

/* 成功提示消息样式 - 与对话框统一风格 */
.success-message {
  position: fixed;
  top: 24px;
  right: 24px;
  padding: 0;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15), 0 0 0 1px rgba(255, 255, 255, 0.1);
  z-index: 5000;
  animation: slideInRight 0.35s cubic-bezier(0.4, 0, 0.2, 1);
  min-width: 320px;
  max-width: 480px;
  overflow: hidden;
  backdrop-filter: blur(10px);
}

.success-message.success {
  background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%);
  border: 1px solid rgba(40, 167, 69, 0.2);
  color: #155724;
}

.success-message.error {
  background: linear-gradient(135deg, #f8d7da 0%, #f5c6cb 100%);
  border: 1px solid rgba(220, 53, 69, 0.2);
  color: #721c24;
}

.success-message.info {
  background: linear-gradient(135deg, #d1ecf1 0%, #bee5eb 100%);
  border: 1px solid rgba(23, 162, 184, 0.2);
  color: #0c5460;
}

.success-message.warning {
  background: linear-gradient(135deg, #fff3cd 0%, #ffeaa7 100%);
  border: 1px solid rgba(255, 193, 7, 0.2);
  color: #856404;
}

.success-content {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 18px 22px;
  position: relative;
}

.success-icon {
  font-size: 22px;
  flex-shrink: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 8px;
  backdrop-filter: blur(10px);
}

.close-success {
  background: rgba(0, 0, 0, 0.08);
  border: none;
  font-size: 20px;
  cursor: pointer;
  margin-left: auto;
  width: 28px;
  height: 28px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
  color: inherit;
  opacity: 0.7;
  flex-shrink: 0;
  font-weight: 300;
  line-height: 1;
}

.close-success:hover {
  opacity: 1;
  background: rgba(0, 0, 0, 0.15);
  transform: scale(1.1) rotate(90deg);
}

.close-success:active {
  transform: scale(0.95) rotate(90deg);
}

@keyframes slideInRight {
  from {
    transform: translateX(400px);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}
</style>
